package com.learn.project.config;

import com.learn.project.enums.DBTypeEnum;
import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author lijiajun
 * @date 2023/11/21
 */
@Slf4j
public class DbContextHolder {

    private static final ThreadLocal<String> CONTEXT_HOLDER = new ThreadLocal<>();

    private static final AtomicInteger COUNTER = new AtomicInteger(-1);

    private static final int MAX_COUNTER = 9999;

    public static void set(String dbSource) {
        // 判断枚举是否为null
        if (null == dbSource) {
            throw new RuntimeException("指定数据源不能不空");
        }
        CONTEXT_HOLDER.set(dbSource);
    }

    public static String get() {
        return CONTEXT_HOLDER.get() == null ? DBTypeEnum.Master.toString() : CONTEXT_HOLDER.get();
    }

    public static void master() {
        log.info(">>>>> 切换到Master");
        set(DBTypeEnum.Master.toString());
    }

    public static void slave() {
        int i = COUNTER.getAndIncrement() % 2;
        if (COUNTER.get() > MAX_COUNTER) {
            COUNTER.set(-1);
        }
        // 如果 i 是单数 切 数据源1
        if (i == 0) {
            log.info(">>>>> 切换到Slave2");
            set(DBTypeEnum.Slave.getValue() + 2);
        } else {
            log.info(">>>>> 切换到Slave1");
            set(DBTypeEnum.Slave.getValue() + 1);
        }
    }

    public static void clear() {
        CONTEXT_HOLDER.remove();
    }


}
